<template>
  <!-- 页面-应用管理-编辑 -->
  <div style="padding: 10px" class="AppEdit-page">
    <Tabs value="name1">
        <TabPane :label="$t('module.appManage.loginSetting')" name="name1">
          <Form :model="modelForm" ref="editForm" :rules="rule" :label-width="200">
            <Row :gutter="32" class="code-row-bg">
              <!-- 应用域名 -->
              <Col span="12">
                <Form-item prop="domainName" :label="$t('module.appManage.appDomainName')">
                  <Input
                    :placeholder="$t('module.appManage.enterdomainName')"
                    v-model="modelForm.domainName"
                    
                    :maxlength="128"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
               <!-- 应用退出地址 -->
              <Col span="12">
                <Form-item prop="webServerRedirectUri" :label="$t('module.appManage.loginoutUrl')">
                  <Input
                    :placeholder="$t('module.appManage.enterLoginoutUrl')"
                    v-model="modelForm.loginOutUri"
                    
                    :maxlength="128"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg">
               <!-- TOKEN有效时长 -->
              <Col span="12">
                <Form-item
                  prop="accessTokenValidity"
                  :label="$t('module.appManage.tokenExpirationTime')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enteraccessTokenValidity')"
                    v-model="modelForm.accessTokenValidity"
                    
                    @on-keyup="checkInputNumber"
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <!-- 是否开启润工作token验证 -->
              <Col span="12">
                <Form-item prop="isOpen" :label="$t('module.appManage.isOpenRunWorkTokenAuth')">
                  <i-switch :true-value="1" :false-value="0" v-model="modelForm.runworkTokenEnabled" true-color="#ff6f4b">
                    <span slot="open">{{$t('module.appManage.open')}}</span>
                    <span slot="close">{{$t('module.appManage.close')}}</span>
                  </i-switch>
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg">
              <!-- 刷新TOKEN周期 -->
              <Col span="12">
                <Form-item
                  prop="refreshTokenValidity"
                  :label="$t('module.appManage.refreshtokenExpirationTime')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterrefreshTokenValidity')"
                    v-model="modelForm.refreshTokenValidity"
                    
                    @on-keyup="checkInputNumber"
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <!-- 是否开启多因子认证 -->
              <Col span="12">
                <Form-item prop="isOpen" :label="$t('module.appManage.EnableMultiFactorAuthentication')">
                  <i-switch :true-value="1" :false-value="0" v-model="modelForm.totpAuthEnabled" true-color="#ff6f4b">
                    <span slot="open">{{$t('module.appManage.open')}}</span>
                    <span slot="close">{{$t('module.appManage.close')}}</span>
                  </i-switch>
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg">
               <!-- 登录方式 -->
              <Col span="12">
                <Form-item prop="loginType" :label="$t('module.appManage.loginType')">
                  <Select
                    :placeholder="$t('module.appManage.enterloginType')"
                    :transfer="true"
                    v-model="modelForm.loginType"
                    
                    class="no-borderColor"
                    :disabled="readOnly"
                  >
                    <Option v-for="itemKey in Object.keys(loginType)" :value="itemKey" :key="itemKey">
                      {{ loginType[itemKey] }}
                    </Option>
                  </Select>
                </Form-item>
              </Col>
              <Col span="12" v-if="modelForm.loginType == 'dadp'">
                <!-- 登录页面地址 -->
                <Form-item :label="$t('module.appManage.loginPageUri')">
                  <Input
                    :placeholder="$t('module.appManage.enterloginPageUri')"
                    v-model="modelForm.loginPageUri"
                    
                     :maxlength="128"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <Col span="12" v-if="modelForm.loginType == 'portal'">
                <!-- 云门户地址 -->
                <Form-item
                  prop="cloudPortalUrl"
                  :label="$t('module.appManage.cloudPortalUrl')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterCloudPortalUrl')"
                    v-model="modelForm.cloudPortalUrl"
                    
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <Col span="12" v-if="modelForm.loginType == 'defined'">
                  <!-- 认证类型 -->
                <Form-item
                  prop="accessTokenValidity"
                  :label="$t('module.appManage.AuthenticationType')"
                  class="accessTokenValidity"
                  
                >
                   <RadioGroup v-model="modelForm.ssoConfigVo.typeCode">
                      <Radio label="OAUTH">
                        <span>OAUTH</span>
                      </Radio>
                      <Radio label="CAS">
                        <span>CAS</span>
                      </Radio>
                  </RadioGroup>
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" v-if="modelForm.loginType == 'portal'">
                 <!-- Csa登录地址 -->
              <Col span="12">
                <Form-item
                  prop="cloudCasLogionUrl"
                  :label="$t('module.appManage.casLoginUrl')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterCasLoginUrl')"
                    v-model="modelForm.cloudCasLogionUrl"
                    
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <!-- Csa退出登录地址 -->
              <Col span="12">
                <Form-item
                  prop="cloudCasOutLogionUrl"
                  :label="$t('module.appManage.casLoginOutUrl')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterCasLoginOutUrl')"
                    v-model="modelForm.cloudCasOutLogionUrl"
                    
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg" v-if="modelForm.loginType == 'portal'">
              <!-- ClientId -->
              <Col span="12">
                <Form-item
                  prop="cloudCasClientId"
                  label="ClientId"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterclientId')"
                    v-model="modelForm.cloudCasClientId"
                    :maxlength="30"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
              <Col span="12">
                 <!-- Secret -->
                <Form-item
                  prop="secret"
                  :label="$t('module.appManage.Secret')"
                >
                  <Input
                    :placeholder="$t('module.appManage.enterSecret')"
                    v-model="modelForm.cloudCasSecret"
                    
                    :maxlength="50"
                    :disabled="readOnly"
                  />
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg" v-if="modelForm.loginType == 'dadp'">
              <Col span="12">
                 <!-- 验证方式 -->
                <Form-item prop="authenticationTypes" :label="$t('module.appManage.verificationMethod')">
                  <CheckboxGroup v-model="modelForm.authenticationTypes">
                      <Checkbox label="PLAT_AUTH">
                        <span>{{$t('module.appManage.platformUsrPassword')}}</span>
                      </Checkbox>
                      <Checkbox label="LDAP_AUTH">
                        <span>{{$t('module.appManage.LdapAuthentication')}}</span>
                      </Checkbox>
                      <Checkbox v-if="modelForm.loginType == 'dadp'" label="THIRD_AUTH">
                        <span>{{$t('module.appManage.thirdPartyAuthentication')}}</span>
                      </Checkbox>
                  </CheckboxGroup>
                </Form-item>
              </Col>
              <Col span="12">
                <!-- 是否开启图形验证码验证 -->
                <Form-item prop="isOpen" :label="$t('module.appManage.isOpenCaptchaAuth')">
                    <i-switch :true-value="1" :false-value="0" v-model="modelForm.captchaEnabled" true-color="#ff6f4b">
                      <span slot="open">{{$t('module.appManage.open')}}</span>
                      <span slot="close">{{$t('module.appManage.close')}}</span>
                    </i-switch>
                  </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg" v-if="modelForm.loginType == 'defined'">
              <Col span="24">
                <RPButton optType="create" class="template-btn"  :text="$t('module.appManage.loadingTemplate')" @click="getTemplate" />
                <RPButton optType="create" class="template-btn"  :text="$t('module.appManage.format')" @click="formatText" />
                <div style="padding: 20px;width: 90%;">
                  <codemirror ref="codemirror1" v-model="modelForm.ssoConfigVo.extConfig" :options="{ ...Options, readOnly: false }"></codemirror>
                </div>

              </Col>
            </Row>
          </Form>
        </TabPane>
        <TabPane :label="$t('module.appManage.dataSynchronizationSettings')" name="name2">
          <Form :model="modelForm" :rules="rule" :label-width="126">
            <Row :gutter="32" class="code-row-bg">
              <Col span="24">
                <Form-item prop="isOpen" :label="$t('module.appManage.mainDataSwitch')">
                  <i-switch v-model="modelForm.isOpen" true-color="#ff6f4b">
                    <span slot="open">{{$t('module.appManage.open')}}</span>
                    <span slot="close">{{$t('module.appManage.close')}}</span>
                  </i-switch>
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="32" class="code-row-bg">
              <Col span="24">
                <!-- 应用数据同步 -->
                <Form-item prop="isOpen" :label="$t('module.appManage.appDataSynchronization')">
                  <i-switch :true-value="1" :false-value="0" v-model="modelForm.isAppDataOpen" true-color="#ff6f4b">
                    <span slot="open">{{$t('module.appManage.open')}}</span>
                    <span slot="close">{{$t('module.appManage.close')}}</span>
                  </i-switch>
                </Form-item>
              </Col>
            </Row>
          </Form>
          <Row :gutter="32" class="code-row-bg" v-if="modelForm.isAppDataOpen">
            <Col span="24">
              <InnerPageTable ref="appTable" :config="tableConfig">
              </InnerPageTable>
            </Col>
          </Row>
        </TabPane>
    </Tabs>
  </div>
</template>
<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/sql/sql' // 引入mode
/** ----------引入theme------------------ */
import 'codemirror/theme/solarized.css'
import 'codemirror/theme/monokai.css'
/** ------------------------------------ */
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/javascript-hint'
import 'codemirror/addon/hint/xml-hint'
import 'codemirror/addon/hint/sql-hint'
import 'codemirror/addon/hint/anyword-hint'
import 'codemirror/addon/scroll/simplescrollbars.css'
import 'codemirror/addon/scroll/simplescrollbars'

import { getUUID } from "@/tools/util.js";
import locales from "./locales.js";
import {
  applicationLoadTemplate,
  applicationConfigQuery,
  applicationConfigCheck,
  applicationConfigUpdate,
  getMainDataStatus,
  openMainDataStatus,
  closeMainDataStatus,
  getSyncType
} from "@/api/applicationApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import { getUserCenterList } from "@/api/userCenterApi.js";
import { CoreModuleName } from "@/const";
import tenantAPI from "@/api/tenantApi.js";
import { codeReg } from "@/const.js";
const CheckUrl = (url) => {
	let reg=/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9\/#.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9\/#.-]+)((?:\/[\+~%\/.\w-_]*))?)$/;
	return !!reg.test(url);
}
export default {
  name: "appedite",
  mixins: [locales],
  components: {
    codemirror
  },
  props: {
    appInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    tenantName: {
      type: String,
      default() {
        return "";
      }
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    tableConfig() {
      return { 
        resource: this.modelForm.syncConfigVoList,
        columns: this.generateColumns.bind(this)(),
        autoFirst: true, //默认 就是 false, 要配置在这里
        isPage: false,
      };
    }
  },
  data() {
    const validateClientId = (rule, value, callback) => {
      if (value === "" || value === null || value === undefined) {
        callback(new Error(this.$t("module.appManage.enterclientId")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const tokenValidity = (rule, value, callback) => {
      if (value == "" || value == null) {
        callback(new Error(this.$t("module.appManage.enteraccessTokenValidity")));
      }
      if (parseFloat(value).toString() == "NaN") {
        callback(new Error(this.$t("module.appManage.warning.tokenValidityNumber")));
      }
      callback();
    };
    const refreshToken = (rule, value, callback) => {
      if (value == "" || value == null) {
        callback(new Error(this.$t("module.appManage.enterrefreshTokenValidity")));
      }
      if (parseFloat(value).toString() == "NaN") {
        callback(new Error(this.$t("module.appManage.warning.requireNumber")));
      }
      callback();
    };
    const domainValidate = (rule, value, callback) => {
      const domain = /^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$/
      const ipv6Reg = /^(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))|\[(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))\](?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/i
      const ipv4Reg = /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/
      console.log(domain.test(value) , ipv4Reg.test(value) , ipv6Reg.test(value));
      if (!domain.test(value) && !ipv4Reg.test(value) && !ipv6Reg.test(value)) {
        callback(new Error(this.$t("module.appManage.enterRightdomainName")));
      }
      callback();
    };

    const { userInfo } = $store.state[CoreModuleName];
    return {
      optionsList: [],
      Options: {
        value: '',
        mode: 'application/json',
        theme: 'blackboard light',
        readOnly: true,
        lineNumbers: true,
        lineWrapping: true,
        extraKeys: { Ctrl: 'autocomplete' },
        autocorrect: true,
        lineWiseCopyCut: true,
        showCursorWhenSelecting: true,
        maxHighlightLength: Infinity,
        matchBrackets: true,
        foldGutter: true,
        autoCloseTags: true,
        matchTags: { bothTags: true },
        styleActiveLine: true,
        smartIndent: true,
        gutters: ['CodeMirror-lint-markers'],
        autoRefresh: true,
        scrollbarStyle: 'native'
      },
      currTenantCode: userInfo.tenantCode || "", //租户编码
      actions: [],
      remoteLoading: false,
      isReadyOnly: false,
      checkedscope: [],
      checkedauthorizedGrantTypes: [],
      userRepositorys: {},
      // scopes: {},
      loginmodes: {},
      loginType: {
        dadp: this.$t("module.appManage.loginTypes.dadp"),
        ldap: this.$t("module.appManage.loginTypes.ldap"),
        portal: this.$t("module.appManage.loginTypes.portal"),
        defined: this.$t("module.appManage.loginTypes.defined")
      },
      clearDataObj: {
        dadp: {
          captchaEnabled: 0,
          authenticationTypes: "",
          loginPageUri: ""
        },
        ldap: {},
        portal: {
          cloudCasLogionUrl: "",
          cloudPortalUrl: "",
          cloudCasSecret: "",
          cloudCasOutLogionUrl: "",
          cloudCasClientId: ""
        },
        defined: {
          ssoConfigVo: {
            clientId: '',
            clientName: '',
            enable: "",
            extConfig: "",
            remark: '',
            typeCode: 'OAUTH',
          },
        }
      },
      languageList: [],
      supportLangs: ["zh-CN"],
      isOpen: false,
      modelForm: {
        clientId: null,
        appName: null,
        userRepository: "default",
        loginOutUri: "",
        domainName: null,
        clientSecretPlaintext: null,
        scope: null,
        webServerRedirectUri: null,
        accessTokenValidity: "6000",
        refreshTokenValidity: "6000",
        authorizedGrantTypes: "password,refresh_token,client_credentials,authorization_code",
        loginType: null,
        authenticationTypes: [],
        validationType: [],
        langs: null,
        tenantName: null,
        enabled: 1,
        isOpen: false,
        runworkTokenEnabled: true,
        totpAuthEnabled: true,
        captchaEnabled: true,
        loginPageUri: "",
        cloudPortalUrl: "",
        cloudCasLogionUrl: "",
        cloudCasOutLogionUrl: "",
        cloudCasClientId: "",
        cloudCasSecret: "", 
        secret: "",
        isAppDataOpen: 0,
        syncConfigVoList: [
          {
            clientId: this.appInfo.clientId,
            syncUrl: '',
            dataCode: '',
          },
        ],
        ssoConfigVo: {
          clientId: '',
          clientName: '',
          enable: "",
          extConfig: "",
          remark: '',
          typeCode: 'OAUTH',
        },
        text: '',
        authType: 'OAUTH',
      },
      rule: {
        cloudCasClientId: [
          {
            required: true,
            validator: validateClientId,
            trigger: "blur"
          },
          // {
          //   type: 'string',
          //   max: 30,
          //   message: this.$t("common.warning.lengMaxFormat", ['30'])
          // }, 
          {
            type: 'string',
            pattern: /^[a-zA-Z0-9|_|\-|\.]+$/,
            message: this.$t("common.warning.codeFormat")
          }
        ],
        loginType: [
          {
            required: true,
            message: this.$t("module.appManage.enterloginType"),
            trigger: "change"
          },
        ],
        appName: [
          {
            required: true,
            message: this.$t("module.appManage.enterappName"),
            trigger: "blur"
          },
          {
            type: 'string',
            max: 64,
            message: this.$t("common.warning.lengMaxFormat", ['64'])
          },
          {
            type: 'string',
            pattern: /[\u4E00-\u9FA5]|[A-Z]|[a-z]|[0-9]/,
            message: this.$t("common.warning.nameFormat")
          }
        ],
        domainName: [
          {
            required: true,
            message: this.$t("module.appManage.enterdomainName"),
            trigger: "blur"
          },
          { validator: domainValidate, trigger: "blur" }
        ],
        clientSecretPlaintext: [
          {
            required: true,
            message: this.$t("module.appManage.enterclientSecret"),
            trigger: "blur"
          }
        ],
        accessTokenValidity: [
          {
            required: true,
            validator: tokenValidity,
            trigger: "blur"
          }
        ],
        refreshTokenValidity: [
          {
            required: true,
            validator: refreshToken,
            trigger: "blur"
          }
        ],
        tenantName: [{ required: true, trigger: "blur" }],
        cloudPortalUrl: [{ required: true, trigger: "blur", message: this.$t("module.appManage.enterCloudPortalUrl"), }],
        cloudCasLogionUrl: [{ required: true, trigger: "blur", message: this.$t("module.appManage.enterCasLoginUrl"), }],
        cloudCasOutLogionUrl: [{ required: true, trigger: "blur", message: this.$t("module.appManage.enterCasLoginOutUrl"), }],
        isOpen: [{ required: true }],
        cloudCasSecret: [{ required: true, trigger: "blur" , message: this.$t("module.appManage.enterSecret"), }],
        authenticationTypes: [{ required: true, message: this.$t("module.appManage.verificationMethod"), }],
      }
    };
  },
  created() {
    this.$emit("SetTitle", this.$t("module.appManage.appSetting"));
    // 调整宽度
    this.$emit("SetPageWidth", 1100);
    if (!this.readOnly) {
      this.actions.push({
        text: this.$t("common.save"),
        theme: "primary",
        handle: () => {
          this.save();
        },
        loading: false
      });
    }
    this.actions.push({
      text: this.$t("common.close"),
      // theme: "primary",
      handle: () => {
        this.$emit("Close");
      }
    });
    this.$emit("SetPageActions", this.actions);
    this.initData();
    this.getMainDataStatus();
  },
  methods: {
    getSyncType() {
      getSyncType({
        appType: this.modelForm.appType || 1
      }).then(res => {
        this.optionsList = res.data
      })
    },
    checkInputNumber(e) {
      e.target.value = e.target.value.replace(/\D/g, "");
    },
    renderOptions(h, options = []) {
      let list = []
      options.forEach(item => {
        list.push(h('Option', {
          props: {
            value: item.dataCode
          }
        }, item.dataDesc))
      })
      return list
    },
    generateColumns() {
      return [
        {
          title: this.$t("module.appManage.dataSelect"),
          key: "dataCode",
          width: 200,
          render: (h, params) => {
            return h('Select', {
              props: {
                value: params.row.dataCode,
                transfer: true
              },
              on: {
                'on-change': (event) => {
                  this.modelForm.syncConfigVoList[params.index].dataCode = event
                }
              }
            }, this.renderOptions(h, this.optionsList))
          }
        },
        {
          title:  this.$t("module.appManage.SyncURL"),
          key: "syncUrl",
          render: (h, params) => {
            return h('Input', {
              props: {
                value: params.row.syncUrl
              },
              on: {
                'input': (val) => {
                  this.modelForm.syncConfigVoList[params.index].syncUrl = val || ''
                },
              }
            })
          }
        },
        {
          title: this.$t("common.operating"),
          align: "left",
          fixed: "right",
          width: 80,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "ios-add",
                    text: this.$t("module.appManage.add"),
                    handle: () => {
                      this.addData(params.row);
                    }
                  },
                  {
                    type: "icon",
                    icon: "ios-trash",
                    text: this.$t("common.delete"),
                    hidden: this.modelForm.syncConfigVoList.length == 1 ? true : false,
                    handle: () => {
                      this.deletedData(params);
                    }
                  }
                ]
              }
            });
          }
        }
      ];
    },
    getTemplate() {
      applicationLoadTemplate({typeCode: this.modelForm.ssoConfigVo.typeCode}).then(res => {
        this.modelForm.ssoConfigVo.extConfig = res.data
      })
    },
    formatText() {
      applicationConfigCheck({typeCode: this.modelForm.ssoConfigVo.typeCode, extConfig: this.modelForm.ssoConfigVo.extConfig}).then(res => {
        if (!res.success) {
          this.$message.error({
            content: res.message || this.$t("common.operateFailed"),
            duration: 3
          });
        } else {
          this.$message.success({
            content: this.$t("module.appManage.templateCheckSuccess"),
            duration: 3
          });
        }
      })
    },
    deletedData(data) {
      this.modelForm.syncConfigVoList.splice(data.index, 1)
    },
    addData() {
      if (this.modelForm.syncConfigVoList.length >=10) {
        this.$message.error({
          content: this.$t("module.appManage.maxLength10"),
          duration: 3
        });
        return false
      }
      this.modelForm.syncConfigVoList.push({
        syncUrl: '',
        dataCode: '',
        clientId: this.appInfo.clientId,
      })
    },
    getMainDataStatus() {
      let { tenantCode, clientId: applicationCode } = this.row;
      getMainDataStatus({
        tenantCode,
        applicationCode
      }).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.isOpen = res.data;
          this.modelForm.isOpen = res.data;
        }
      });
    },
    getClientSecret() {
      let temp = getUUID().replace(new RegExp("-", "g"), "");
      this.modelForm.clientSecretPlaintext = temp;
    },
    async initData() {
      // if()
      // this.searchScope();
      //获取产品类型
      const result = await Promise.all([valueSetAPI.getValueSetByCode("LOGIN_MODE"), getUserCenterList()]);
      //   结构赋值
      const [dicArrLogin, { data: userTemp }] = result;
      this.loginmodes = {};
      for (let i = 0; i < dicArrLogin.length; i++) {
        let diclogin = dicArrLogin[i];
        this.loginmodes[diclogin.vsiKey] = diclogin.vsiValue;
      }
      this.userRepositorys = {};
      for (let i = 0; i < userTemp.length; i++) {
        let temp = userTemp[i];
        this.userRepositorys[temp.userCenterId] = temp.userCenterName;
      }

      if (!!this.appInfo.id) {
        this.isReadyOnly = true;
        this.getDataById();
      }

      // 语言清单
      valueSetAPI.getValueSetByCode("languageList").then(data => {
        for (const lang of data) {
          this.languageList.push({
            langDesc: lang.vsiValue,
            langCode: lang.vsiKey
          });
        }
      });
      //新增时
      if (!this.appInfo.id) {
        this.modelForm.tenantName = this.tenantName;
      }
    },
    getDataById() {
      applicationConfigQuery({tenantCode: this.appInfo.tenantCode, applicationCode: this.appInfo.clientId})
        .then(response => {
          Object.assign(this.modelForm, response.data);
          this.modelForm.accessTokenValidity = this.modelForm.accessTokenValidity + ""; //处理校验问题
          this.modelForm.refreshTokenValidity = this.modelForm.refreshTokenValidity + ""; //处理校验问题
          this.modelForm.authenticationTypes = response.data.authenticationTypes ? response.data.authenticationTypes.split(',') : []
          if (!this.modelForm.ssoConfigVo.typeCode) {
            this.modelForm.ssoConfigVo.typeCode = 'OAUTH'
          }
          if (this.modelForm.syncConfigVoList && this.modelForm.syncConfigVoList.length > 0) {
            this.modelForm.isAppDataOpen = 1
          }
          if (!this.modelForm.syncConfigVoList || this.modelForm.syncConfigVoList.length == 0) {
            this.modelForm.syncConfigVoList = [{
            syncUrl: '',
            dataCode: '',
            clientId: this.appInfo.clientId,
            }]
          }
          const res = response.data;
          this.getSyncType()
          // this.modelForm.tenantName = res.tenantCode;
          this.initTenant(res.tenantCode); //获取租户编码对应的租户名称
          if (this.modelForm.scope) {
            this.checkedscope = this.modelForm.scope.split(",");
          }
          if (this.modelForm.langs) {
            this.supportLangs = this.modelForm.langs.split(",");
          }
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant(tenantCode) {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (tenantCode == tenant.tenantCode) {
            this.modelForm.tenantName = tenant.tenantName;
          }
        }
      });
    },
    openOrCloseMainDataStatus() {
      let params = {
        applicationCode: this.modelForm.clientId,
        tenantCode: this.currTenantCode
      };
      if (this.appInfo.id) {
        // 编辑
        if (this.modelForm.isOpen === this.isOpen) {
          return false;
        }
        if (this.modelForm.isOpen) {
          // 开启
          openMainDataStatus(params).then(res => {
            console.log(res, "openMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        } else {
          // 关闭
          closeMainDataStatus(params).then(res => {
            console.log(res, "closeMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        }
      } else {
        // 新建
        if (this.modelForm.isOpen) {
          // 开启
          openMainDataStatus(params).then(res => {
            console.log(res, "openMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        }
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        let submitForm = Object.assign({}, this.modelForm)
        let dataListCheck = true
        if (submitForm.isAppDataOpen && submitForm.syncConfigVoList.length) {
          dataListCheck = !submitForm.syncConfigVoList.find(item => !item.dataCode || !item.syncUrl || !CheckUrl(item.syncUrl))
        }
        if (!dataListCheck) {
          this.$message.error({
            content: this.$t("module.appManage.appDataValidateFailed"),
            duration: 3
          });
          return false
        }
        if (valid && dataListCheck) {
          this.actions[0].loading = true;
          if (!submitForm.isAppDataOpen) {
            submitForm.syncConfigVoList = []
          } else {
            if (submitForm.syncConfigVoList.find(item => !item.dataCode || !item.syncUrl)) {
                this.$message.error({
                  content: this.$t("module.appManage.appDataCheck"),
                  duration: 3
                });
                this.actions[0].loading = false;
                return false
            }
          }
          if (this.checkedscope.length > 0) {
            submitForm.scope = this.checkedscope.join();
          }
          if (this.supportLangs.length > 0) {
            submitForm.langs = this.supportLangs.join(",");
          }

          submitForm.accessTokenValidity = parseFloat(submitForm.accessTokenValidity);
          submitForm.refreshTokenValidity = parseFloat(submitForm.refreshTokenValidity);
          submitForm.authenticationTypes = submitForm.authenticationTypes.join(',')

        //  for(let key in this.clearDataObj) {
        //   if (key !== submitForm.loginType) {
        //     for (let key1 in this.clearDataObj[key]) {
        //       submitForm[key1] = this.clearDataObj[key][key1]
        //     }
        //   }
        //  }

         if (submitForm.loginType == 'defined' && !submitForm.ssoConfigVo.clientId) {
          submitForm.ssoConfigVo.clientId = submitForm.clientId
          submitForm.ssoConfigVo.clientName = submitForm.appName
         }
          applicationConfigUpdate(submitForm)
            .then(response => {
              this.actions[0].loading = false;
              this.openOrCloseMainDataStatus(); // 主数据同步
              const content = this.appInfo.id
                ? this.$t("module.valueSet.updateSuccess")
                : this.$t("module.valueSet.createSuccess");
              this.$message.success({
                content: content,
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(err => {
              this.actions[0].loading = false;
            });
        } else {
          this.$message.error({
            content: this.$t("module.valueSet.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    }
  },
  watch: {
    //切换登录类型  重置云门户地址字段
    'modelForm.loginType': {
      handler(val, old) {
        if (old == 'portal' && !this.modelForm.cloudPortalUrl) {
          this.$refs['editForm'].fields.forEach(item => {
            if (item.prop === 'cloudPortalUrl') {
              item.resetField()
            }
          })
        }
      }
    },
    'modelForm.isAppDataOpen': {
        handler(val) {
        if (!val) {
           this.modelForm.syncConfigVoList = [{
            url: '',
            dataCode: '',
          }]
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.AppEdit-page {
  .accessTokenValidity,
  .refreshTokenValidity {
    .ivu-input-wrapper {
      width: calc(~"100% - 14px") !important;
    }
  }
  /deep/.ivu-tabs-nav {
    .ivu-tabs-ink-bar {
      background-color: #f76c4b!important;
    }
  }
  /deep/.vue-codemirror {
    border: 2px solid #eee
  }
}
/deep/.check-error {
  border: 1px solid red;
}
.template-btn {
  color: #fff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
  margin-right: 10px;
}
</style>
